<?php
/*
//----------------------------------------------------------
//----------- CHANGEABLE PART ------------------------------
//----------------------------------------------------------

require_once("../../class2.php");
require_once(HEADERF);
		$user_id = USERID;
		$user_name = USERNAME;
require_once("./includes/require_all.php");

ramka("open");

//Common variables
$CMS_file = $_GET['name'];
$CMS_page = get_page();
$posted= $_POST['comment'];

		$per_page = $page_rows; //Number of rows to be displayed on 1 page
		$offset = $per_page*($CMS_page - 1); //Offset for the pages

//System functions
$pages=CMS_gamePagerInitiate();
CMS_dictionarySave();

//----------------------------------------------------------
//----------- UNCHANGEABLE PART ----------------------------
//----------------------------------------------------------
//---> Load text arrays for translation
$rows = mysql_query("SELECT * FROM $text_table WHERE file_name = '$CMS_file' and content <> '' LIMIT $per_page OFFSET $offset");
$arr_textid= array(); $arr_echoid= array(); $arr_translators= array(); $arr_content= array(); $arr_bg= array(); $arr_en= array(); $arr_en_slashed= array(); $key=0;
while($row = mysql_fetch_array($rows)){
		$content = trim($row['content']); //Removing any spacebars from both ends
		$content = preg_replace("/\n/", " ", $content); //Removing any new lines
		$content = preg_replace("/</", "&lt", $content);
		$content2 = trim($row['english']); //Removing any spacebars from both ends
		$content2 = preg_replace("/\n/", " ", $content2); //Removing any new lines
		$text_id = $row['text_id'];
		$textarea = str_replace("[", "--IC001--", $text_id);
		$textarea = str_replace("]", "--IC002--", $textarea);
		$textarea = str_replace(":", "--IC003--", $textarea);
		$textarea = str_replace(" ", "--IC004--", $textarea);
		$textarea = str_replace("'", "--IC005--", $textarea);
		$translator= $row['translator'];
		$arr_textid[$key]= $textarea;
		$arr_echoid[$key]= $text_id;
		$arr_translators[$key]= $translator;
		$arr_content[$key]= $row['content'];
		$arr_bg[$key]= $content;
		$arr_en[$key]= $content2;
		$arr_en_slashed[$key]= addslashes($content2);
		$key++;
} unset($key);

//---> Record the posted translation
if(isset($_POST['submit'])){
	$temp = ''; //Temporary file for containing transformed text for user translation
	$strcount=0;
	foreach ($arr_textid as $k => $w) {
		if(isset($_POST['translation_'.$w]) and preg_match("/[а-яА-Я]{2,}/u", $_POST['translation_'.$w]) and !preg_match("/(<script)/", $_POST['translation_'.$w])){
				$strcount++;
				$tran = punctuation_check($_POST['translation_'.$w]);
				if(preg_match("/\</", $tran)){
					$tran = preg_replace("/</", "&lt;", $tran);
				}
				$temp .= $arr_echoid[$k]."=>".$tran."\n";
			}
		}
	if(strlen($temp) > 0){
		$temp = mysql_real_escape_string($temp);
		$sql_sign_translation = "INSERT INTO $translations_table (translation, file_name, translator_id, translator_name, page) VALUES ('$temp', '$CMS_file', '$user_id', '$user_name', '$CMS_page')";
		mysql_query($sql_sign_translation);
		CMS_statistic1SAVE($strcount);
	}
}
unset ($temp, $tran);

//---> Load translated ids for for yellow, green and red markings
$rows = mysql_query("SELECT translation FROM $translations_table WHERE file_name = '$CMS_file' and page = '$CMS_page'");
while($row = mysql_fetch_array($rows)){
	if($row['translation'] != ''){
			$temp = explode("\n", $row['translation']); //Dividing user's translation into rows
			foreach($temp as $v){
				$part = explode("=>", $v);
				$arr_transids[] = $part[0];
				$arr_transes[] = $part[1];
			}
	}
}
unset ($rows, $row, $temp, $v, $part);

CMS_gamePagerOverall_Save($arr_content, $arr_echoid);

//---> Back-button, page-tittle and legend
echo <<<HTML
	<center><br>
	<h1 style="font-size:18px;" class="unselectable">$gamename ($CMS_file, стр.$CMS_page)</h1>
	</center>
	<table class="cmsMenu"><tr>
	<td class="cmsMenuDivider unselectable"><<</td>
	<td class="cmsMenuTab cmsMenuTab-back unselectable" onclick="javascript: window.location='viewtext.php?game=$CMS_game&name=$CMS_file&page=$CMS_page';">НАЗАД</td>
	<td class="cmsMenuDivider unselectable">||</td>
	<td class="cmsMenuTab unselectable" onclick="javascript:toggle('legend001'); toggle3('search001'); toggle3('dict001');">Легенда</td>
	<td class="cmsMenuDivider unselectable">||</td>
	<td class="cmsMenuTab unselectable" onclick="javascript:toggle('search001'); toggle3('legend001'); toggle3('dict001');">Търсачка</td>
	<td class="cmsMenuDivider unselectable">||</td>
	<td class="cmsMenuTab unselectable" onclick="javascript:toggle('dict001'); toggle3('legend001'); toggle3('search001');">Речник</td>
	<td class="cmsMenuDivider unselectable">>></td>
	</tr></table>

	<div id="legend001" style="display: none">
		<br>
		<img src="icons/edit1.png"> Позволява да се добави нов превод на вече одобрена реплика<br>
		<img src="icons/eng2.png"> Изтрива съдържанието на полето и въвежда английския текст на репликата заедно с код, който позволява тя да бъде одобрена като преведена. N.B: Ако натиснете по погрешка бутона и изгубите преведения в полето текст, шракнете с мишката вътре в полето и натиснете CTRL+Z.<br>
		<span style='color:green;'>[...]</span><span style='color:red;'>[...]</span>Текстът в квадратните скоби не се превежда и не е необходимо да се добавя в полето за писане на превода. В зависимост от играта, той може да показва кой говори, къде се развива действието и т.н. <span style='color:red;'><br>Червеният</span> цвят означава, че репликата не е преведена, а <span style='color:green;'>зеленият</span> е похвала за добре свършената работа :).
		N.B. Рефрешът на страницата няма да изтрие съдържанието на полетата. Направено е нарочно така, за да не се изгуби случайно текстът.
	</div>
HTML;

//--------------------------------------------------------------------
//------------------- SEARCH EMGINE ----------------------------------
//--------------------------------------------------------------------
//------------------- HTML visualization of the search engine
echo <<<HTML
	 <div id="search001" style="display: none;">
		 <br>
		 <form name="search" method="post" action="search.php?game=$CMS_game&go=yes" target="_blank">
		 <b>Търси: </b><input type="text" name="find" class="cmsTextarea"/><b> в </b> 
		 <Select NAME="field" class="cmsTextarea">
		 <Option VALUE="english">Оригиналния текст</option>
		 <Option VALUE="content">Преведените реплики</option>
		 </Select>
		 <input type="hidden" name="searching" value="yes" />
		 <input type="submit" name="search" value="Намери" class="cmsButtonStandart"/>
		 <br>
			 <input type="checkbox" name="capses" value="yes" >Големи/малки букви
			 <input type="checkbox" name="wholewords" value="yes" checked>Цели думи
		 </form>
	 </div>
HTML;
//------------------- Search executes in new page (where code is) ----
//------------------- SEARCH EMGINE END ------------------------------
//--------------------------------------------------------------------

echo '<div id="dict001" style="display: none">';
	CMS_dictionaryEcho();
echo '</div>';

$dict= CMS_dictionaryLoad();
$arr_bg2= CMS_insertDictTooltips($dict, $arr_en);


if($strcount>0) {
	echo "<br><center><div style= 'color:black; border: 1px solid #FFF; border-radius: 1px; border-color: red; background:yellow;'><b> Репликите бяха запазени. Благодарим ви! </b></div></center>"; }	
CMS_lastApprovedEcho();

echo "<br>";
//---> Show form for acquiring translations
if($user_rights["ADD"]===1){
	$text = ''; //It will contain the untranslated text for the edittext.php
	echo '<form action="" method="post" style="display: inline;">';
	echo "<div onmouseup=\"javascript:getSelText('keyword');\"><TABLE style='float:left;' CELLSPACING='0' CELLPADDING ='4' WIDTH='100%'>";
	foreach ($arr_echoid as $key => $value) {
		$text_id= $value; $content= $arr_bg[$key]; $content2= $arr_en[$key]; $content_slashed= $arr_en_slashed[$key]; $translator= $arr_translators[$key]; $content_tooltiped= $arr_bg2[$key];
		$bg_escaped=str_replace('"', "&quot;", $content); $bg_escaped=str_replace("'", "\'", $bg_escaped); $bg_escaped=str_replace("  ", " ", $bg_escaped);
		$textarea= $arr_textid[$key];
		if ($key%2==1) { $class= "cmsRow1"; } else { $class= "cmsRow2"; }
		if(preg_match("/[а-яА-Я]{2,}/u", $content) OR preg_match("/(_IGcoLLen){1}/", $text_id)){
			echo <<<HTML
			<tr>
			<td style="vertical-align:top;" WIDTH="2%">
			<img src="icons/bullet-green.png" class="unselectable" alt="$"/>
			</td><td class="$class">
			<span id="main_$text_id" style="color:green;"></span> $content 
			(<span style="color:white;" class="unselectable">$translator</span>)
			<br>
			<div id="toggleText_$text_id">
			<span id="main2_$text_id" style='color:black;'></span> <span style='color:yellow;'>$content_tooltiped </span><br>
			<textarea name="translation_$textarea" cols="85" id="trans_$textarea" 
						style="color:white; border: 1px solid #FFF; border-radius: 1px; border-color: green;
						background:black; margin-top:-1px; margin-bottom:5px;"
						class="expand"
						onfocus="javascript:toggleSpan('main_$text_id', '[$text_id]'); toggleSpan('main2_$text_id', '[$text_id]');"
						onblur="javascript:toggleSpan('main_$text_id', ''); toggleSpan('main2_$text_id', '')"
						onclick="javascript:autoInsert('trans_$textarea', '$bg_escaped');"></textarea>
			<a onClick="document.getElementById('trans_$text_id').value = '$content_slashed(IC101: Остави английския текст)'"><img src="icons/eng2.png" style='margin-top:-1px; margin-bottom:5px;' alt="Добави" /></a>
			<br>
			</div>
			</td></tr>
HTML;
		}
		else{
				if (in_array($text_id, $arr_transids)) { $icon= "bullet-yellow.png"; $color= "yellow"; } else { $icon= "bullet-red.png"; $color= "red"; }
			$text .= $text_id."=".$content."\n";
			echo <<<HTML
			<tr>
			<td style="vertical-align:top;" WIDTH="2%">
			<img src="icons/$icon" alt="$" class="unselectable"/>
			</td><td class="$class">
			<span id="main_$text_id" style="color:$color;"></span> $content_tooltiped
			<br>
			<textarea name="translation_$textarea" cols="85" rows="1" id="trans_$textarea" 
						style="color:white; border: 1px solid #FFF; border-radius: 1px; border-color: gray;
						background:black; margin-top:-1px; margin-bottom:5px;"
						class="expand"
						onfocus="javascript:toggleSpan('main_$text_id', '[$text_id]')"
						onblur="javascript:toggleSpan('main_$text_id', '')"></textarea><span id="unneeded" class="unselectable"> </span>
			<a onClick="document.getElementById('trans_$textarea').value = '$content_slashed(IC101: Остави английския текст)'"><img src="icons/eng2.png" style='margin-top:-1px; margin-bottom:5px;' alt="Добави" /></a>
			<br>
			</td></tr>
HTML;
		}
	}
		echo '</TABLE></div>';
		echo '<br><center style="clear: left;" class="unselectable"><input name="submit" type="submit" value="Изпрати" class="cmsButtonStandart">';
		echo '</form>';
		echo '</center>';
		echo '<br><br>';
	
//---> Alpha-pager (Previous|Present|Next)		
		$p_prev=$CMS_page-1; $p_next=$CMS_page+1;
		if ($pages>1)
		{
			echo '<center class="unselectable">';
			if ($p_prev>0 AND $p_prev<=$pages) {
			echo "<a href='edittext.php?game=$CMS_game&name=$CMS_file&page=$p_prev'><img src='icons/previous.png' alt='Предишна' style='vertical-align:middle;'/></a>";};
			echo "<a style='color:white;'><b>$CMS_page</b></a>";
			if ($p_next>0 AND $p_next<=$pages) {
			echo "<a href='edittext.php?game=$CMS_game&name=$CMS_file&page=$p_next'><img src='icons/next.png' alt='Следваща' style='vertical-align:middle;'/></a>";};	
			echo "</center>";
			echo "<h1></h1>";
		}
		
//---> Counting the comments
		$num_notes= mysql_fetch_array (mysql_query("SELECT COUNT(*) FROM cms_notes WHERE game = '$CMS_game'"));
		$num_notes= $num_notes['0'];
		
//---------------------------- SECOND MENU START ------------------------------------
echo <<<HTML
				<center>
				<h1></h1>
				<table class="cmsMenu cmsMenu2 unselectable"><tr>
				<td class="cmsMenuDivider"><<</td>
				<td class="cmsMenuTab cmsMenuTab-back" onclick="javascript: window.location='viewtext.php?game=$CMS_game&name=$CMS_file&page=$CMS_page';">НАЗАД</td>
				<td class="cmsMenuDivider">||</td>
				<td class="cmsMenuTab" onclick="javascript:toggle2('pages001'); toggle3('transes001'); toggle3('comments001');">Страници</td>
				<td class="cmsMenuDivider">||</td>
				<td class="cmsMenuTab" onclick="javascript:toggle2('transes001'); toggle3('pages001'); toggle3('comments001');">Преводи</td>
				<td class="cmsMenuDivider">||</td>
				<td class="cmsMenuTab" onclick="javascript:toggle2('comments001'); toggle3('pages001'); toggle3('transes001');">Бележки: <b class="cmsNumNotes"> $num_notes </b></td>
				<td class="cmsMenuDivider">>></td>
				</tr></table>
				</center>
				<br>
HTML;
//---------------------------- SECOND MENU END ------------------------------------

//---> Alpha-pager (Page list)
if($_GET['go'] != "pending" AND $_POST['editoract'] != "yes") { echo "<div id='pages001' style='display:block'>"; }
else { echo "<div id='pages001' style='display:none'>"; }
	$all_pages_array = array(); $pages_array = array();
	$pages_status= CMS_gamePagerOverall_Load();
	for($i=1;$i<=$pages;$i++){ 
		if ($i==$CMS_page) { $pages_array[] = "cmsPager cmsWHITE"; }
		elseif ($pages_status[$i]== "yellow") { $pages_array[] = "cmsPager cmsYELLOW"; }
		elseif ($pages_status[$i]== "green") { $pages_array[] = "cmsPager cmsGREEN"; }
		else { $pages_array[] = "cmsPager cmsRED"; }
		}
	$per = 0;
	if ($pages>999) {$TDwitdh="35px";$cons=18;} elseif ($pages>99) {$TDwitdh="25px";$cons=24;} else {$TDwitdh="15px";$cons=34;}; // Набързо скалъпвам широчината и броя на колоните в pager-а, съобразно броя на страниците, за да са с еднаква ширина бутоните в него
	echo "<table style='text-align:center;'><tr>";
	for($i=1;$i<=$pages;$i++){
		if($per%$cons == 0){
			echo "</tr>";
		}
		if($per%$cons == 0){
			echo "<tr>";
		}
		$a= $i-1; $TDcolor= $pages_array[$a];
			echo <<<HTML
					<td class='$TDcolor unselectable' style='width:$TDwitdh;'
					onclick="javascript: window.location='edittext.php?game=$CMS_game&name=$CMS_file&page=$i';">$i</td>
HTML;
		$per++;
	}
	echo "</table><br>";
echo "</div>";

//---> Approve/Disapprove status or delete the translation
if($_GET['go'] === "pending" OR $_POST['editoract'] === "yes") { echo "<div id='transes001' style='display:block'>"; }
else { echo "<div id='transes001' style='display:none'>"; }
	$result_all_id = mysql_query("SELECT id FROM $translations_table");
	while($array_all_id = mysql_fetch_array($result_all_id)){
		$id_translation = array_shift($array_all_id);
		if(isset($_POST["approve_$id_translation"])){
			$trans = $_POST["trans_$id_translation"];
			mysql_query("UPDATE $translations_table SET status = 'Одобрен', translation = '".mysql_real_escape_string($trans)."' WHERE id = '$id_translation' AND file_name = '$CMS_file'");
			
			$translator= mysql_query("SELECT translator_name FROM $translations_table WHERE id = '$id_translation' LIMIT 1");
			$translator= mysql_fetch_array($translator);
			$translator= $translator['translator_name'];
			
			$translation = explode("\n", $trans); //Dividing user's translation into rows
			$count= count($translation);
			$codes = array(); //It will contain codes from user's translation
			foreach($translation as $v){
				$g = explode("=>", $v);
				$codes[] = $g[0];
			}
			foreach($codes as $key => $code){
				$code_repl= 0;
				$t = explode("=>", $translation[$key]);
				if (preg_match("/(_IGcoLLen)/", $code)) { $code_repl= str_replace ("_IGcoLLen", "", $code);};
				if (preg_match("/(IC101: Остави английския текст)/", $t[1])) {  // Сменяме text_id-то на файла, за да бъде считан низът оттук-нататък като преведен
					$t[1]= str_replace ("(IC101: Остави английския текст)", "", $t[1]);
					if ($code_repl!==0) {$code_repl= $code_repl."_IGcoLLen";};
					if ($code_repl===0) {$code_repl= $code."_IGcoLLen";};
				}
				$code= mysql_real_escape_string($code);
				if ($code_repl!==0) {
					$code_repl= mysql_real_escape_string($code_repl);
					mysql_query("UPDATE $text_table SET text_id = replace(text_id, '$code', '$code_repl') WHERE text_id = '$code' AND file_name = '$CMS_file'");
					$code= $code_repl;
				}
				$s= array_search($code, $arr_echoid); $translator_back= $translator;
				if ($arr_translators[$s]!="original") { $translator=$arr_translators[$s]; }
				mysql_query("UPDATE $text_table SET content = '".mysql_real_escape_string($t[1])."', translator = '".mysql_real_escape_string($translator)."' WHERE text_id = '$code' AND file_name = '$CMS_file'");
				$translator= $translator_back;
				
				//translating all the same rows
				$x = mysql_query("select * from $text_table where text_id = '$code' and file_name = '$CMS_file'");
				$y = mysql_fetch_array($x);
				$id = $y['text_id'];
				$eng = $y['english'];
				$bg = $y['content'];
				$tr = $y['translator'];
				$rrr = mysql_query("select * from $text_table where english = binary '".mysql_real_escape_string($eng)."' and translator = 'original'");
				if(mysql_num_rows($rrr)){
					if(preg_match("/(_IGcoLLen)/", $id)){
						mysql_query("UPDATE $text_table SET text_id = concat(text_id, '_IGcoLLen'), content = '".mysql_real_escape_string($bg)."', translator = '".mysql_real_escape_string($tr)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator = 'original'");
					}
					else{
						mysql_query("UPDATE $text_table SET content = '".mysql_real_escape_string($bg)."', translator = '".mysql_real_escape_string($tr)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator = 'original'");
					}
				}
			}
			CMS_lastApprovedSave($count, $translator);
			echo "<meta http-equiv=\"refresh\" content=\"0;edittext.php?game=$CMS_game&name=$CMS_file&page=$CMS_page\" />";
		}
		if(isset($_POST["disapprove_$id_translation"])){
			mysql_query("UPDATE $translations_table SET status = 'Неодобрен' WHERE id = '$id_translation'");
		}
		if(isset($_POST['delete_'.$id_translation])){
			mysql_query("DELETE FROM $translations_table WHERE id = '$id_translation'");
		}
	}
	
//---> Show all recorded translation for that text in that page
	$result_translations = mysql_query("SELECT * FROM $translations_table WHERE file_name = '$CMS_file' and page = '$CMS_page' ORDER BY id DESC");
	while($array_translations = mysql_fetch_array($result_translations)){
		if($user_rights["ADD"]===1 AND $user_rights["APPROVE"]!==1){
			$status = $array_translations['status'];
			if($status === 'Одобрен'){ $status_color = "green"; } elseif($status === 'Неодобрен'){ $status_color = "red"; } else { $status_color = "yellow"; }
			echo "<table><tr><td>";
			echo "<div style='border: 1px solid #FFF; padding: 5px; margin: 2px 0px; width: 725px; border-radius: 7px; border-color: $status_color'; id='".$array_translations['id']."'>";
			echo "<a href=/user.php?id.".$array_translations['translator_id']." name=".$array_translations['id'].">".$array_translations['translator_name']."</a> <span class='smalltext' style='float: right;'>".$array_translations['time']."</span><br />";
			echo nl2br($array_translations['translation']);
			$status = $array_translations['status'];
			echo "<br><span style='color: $status_color;'>".$status."</span><br />";
			echo "</div>";
			echo "</td></tr></table>";
		}
		
//---> Show translsation areas for admin + Approve/disapprove/delete translations
		if($user_rights["APPROVE"]===1){
			$tran = ''; $pretran = '';
			$status = $array_translations['status'];
			$waiting_text = trim($array_translations['translation']);
				$waiting_rows = explode("\n", $waiting_text);
				foreach ($waiting_rows as $row) {
					$exploded = explode("=>", $row);
					$waiting_id[] = $exploded[0];
				}
				foreach ($waiting_id as $v) {
					$key = array_search($v, $arr_echoid, true);
					$pretran .= "<span style='color:yellow'>".$arr_echoid[$key]."=</span>".$arr_content[$key]."<br>";
				}
				unset ($waiting_rows, $exploded, $waiting_id); 
			if($status == 'Одобрен'){ $status_color = "green"; } elseif($status == 'Неодобрен'){ $status_color = "red"; } else { $status_color = "yellow"; }
			echo "<table><tr><td>";
			echo "<div style='border: 1px solid #FFF; padding: 5px; margin: 2px 0px; width: 725px; border-radius: 7px; border-color: $status_color' id='".$array_translations['id']."'>";
			echo "<a href=/user.php?id.".$array_translations['translator_id'].">".$array_translations['translator_name']."</a> <span class='smalltext' style='float: right;'>".$array_translations['time']."</span><br /><br />";
			echo '<form action="" method="post">';
				if ( $_GET['go']=="pending" ) {
					echo '<textarea name="trans_'.$array_translations['id'].'" cols="87" id="trans" class="expand24-168" style="background:#a1a1a1; font-size:10;">'.$waiting_text.'</textarea> </br>';
				}
				else {
					echo '<textarea name="trans_'.$array_translations['id'].'" cols="87" rows= "3" id="trans" style="background:#a1a1a1; font-size:10;" class="expand24-168">'.$waiting_text.'</textarea> </br>';
				}
			echo '<a style="color:white">Настоящо състояние на репликите: </a>(<a href="javascript:toggle(\'tip_'.$array_translations['id'].'\');">Покажи</a>)';
			echo '<div id="tip_'.$array_translations['id'].'" style="display: none">';
			echo $pretran;
			echo '</div>';
			echo "<br><span style='color: $status_color;'>".$status."</span><br />";
			echo '<input type="hidden" name="editoract" value="yes">';
			if($status == 'Одобрен'){
				echo '<input name="approve_'.$array_translations['id'].'" type="submit" value="Одобри" style="text-decoration: line-through;" disabled>';
				echo '<input name="disapprove_'.$array_translations['id'].'" type="submit" value="Отхвърли" style="text-decoration: line-through;" disabled>';
			}
			elseif($status == 'Неодобрен'){
				echo '<input name="approve_'.$array_translations['id'].'" type="submit" value="Одобри">';
				echo '<input name="disapprove_'.$array_translations['id'].'" type="submit" value="Отхвърли" style="text-decoration: line-through;" disabled>';
			}
			else{
				echo '<input name="approve_'.$array_translations['id'].'" type="submit" value="Одобри">';
				echo '<input name="disapprove_'.$array_translations['id'].'" type="submit" value="Отхвърли">';
			}
			echo '<input name="delete_'.$array_translations['id'].'" type="submit" value="Изтрий">';
			
			echo '</form>';
			echo "</div>";
			echo "</td>";
			echo "</tr>";
			echo "</table>";
		}
	}
echo "</div>";

if(isset($_POST['comsubmit'])) { echo "<div id='comments001' style='display:block'>"; }
else { echo "<div id='comments001' style='display:none'>"; }
			if (isset($posted)) {
				$posted = strtoupper($posted); 
				$posted = strip_tags($posted); 
				$posted = trim ($posted);
			}
			if(isset($_POST['comsubmit']) AND $posted != '') {
				mysql_query("INSERT INTO cms_notes (`note`, `game`, `user_id`, `user_name`) VALUES ('$posted', '$CMS_game', '$user_id', '$user_name')");
			}			

			$temp=0;
			$notes= mysql_query("SELECT * FROM cms_notes WHERE game = '$CMS_game' ORDER by time DESC");
			while($note = mysql_fetch_array( $notes )) {
				$arr_notes[$temp]['note']= $note['note'];
				$arr_notes[$temp]['status']= $note['status'];
				$arr_notes[$temp]['time']= $note['time'];
				$arr_notes[$temp]['user']= $note['user_name'];
				$temp++;
			}
			
			if ($temp == 0) { echo "<center style='color:white;'>Все още няма добавени бележки.</center>"; }
			echo "<div class='cmntBody'>";
			$temp=1;
			foreach ($arr_notes as $key => $note) {
				  if ($temp%2===0) { $class= "cmntRow1"; $class2= "cmntUser1"; } else { $class= "cmntRow2"; $class2= "cmntUser2"; }
				  echo "<div class='$class'><span class='$class2'>".$note['user']."</span> <span class='cmntDate'>".$note['time']."</span><br>";
				  echo "<img src='icons/bullet-white.png' alt=' ' class='unselectable'/> ".$note['note']."<br>";
				  echo "</div>";
				  $temp++;
			}
			echo "</div>";
			echo "	
					<form method='post' action='edittext.php?game=$CMS_game&name=$CMS_file&page=$CMS_page#menu2'>
					<br><center><textarea name='comment' cols='50' id='comment' class='cmntField expand16-100'></textarea>
					<br><input type='submit' value='Изпрати' name='comsubmit'></center>
					</form><br /> 
				 ";
echo "</div>";
echo "<h1></h1>";

$translationButtons= "";
if($user_rights["APPROVE"]===1){
	$pendings= CMS_pendingTranslationsLoad("for game");
	if (!isset($_GET['pendingID'])) {
		$filestart= array_search($CMS_file, $pendings);
		foreach ($pendings as $index => $pending) {
			if ($pending['page']<$CMS_page AND $pending['file_name']==$CMS_file) {$prev_key= $index;}
			elseif ($pending['page']>=$CMS_page AND $pending['file_name']==$CMS_file) {$next_key= $index; break;}
			else {
					$temp= $filestart-1;
					if (isset($pendings[$temp])) { $prev_key= $temp; }
					$temp= $filestart+1;
					if (isset($pendings[$temp])) { $next_key= $temp; }
			}
		}
	}
	else {
		$present= $_GET['pendingID'];
		$temp= $present-1;
		if (isset($pendings[$temp])) { $prev_key= $temp; }
		$temp= $present+1;
		if (isset($pendings[$temp])) { $next_key= $temp; }
	}
	$tmp_name= $pendings[$prev_key]['file_name']; $tmp_page= $pendings[$prev_key]['page']; $tmp_id= $pendings[$prev_key]['id'];
	if (isset($prev_key)) {$prev="viewtext.php?game=$CMS_game&name=$tmp_name&page=$tmp_page&pendingID=$prev_key&go=pending#$tmp_id";}
	$tmp_name= $pendings[$next_key]['file_name']; $tmp_page= $pendings[$next_key]['page']; $tmp_id= $pendings[$next_key]['id'];
	if (isset($next_key)) {$next="viewtext.php?game=$CMS_game&name=$tmp_name&page=$tmp_page&pendingID=$next_key&go=pending#$tmp_id";}
	if (isset($prev)) {$translationButtons.="<a href='$prev' style='vertical-align:middle;'>◄</a>";}
	$translationButtons.="<span class='cmsPendingTranses' style='vertical-align:middle;'>".$pendings['count']."</span>";
	if (isset($next)) {$translationButtons.="<a href='$next' style='vertical-align:middle;'>►</a>";}
	$translationButtons= "<span style='color:#0D0D0D;' class='unselectable'>|| </span>".$translationButtons;
}
	
echo <<<HTML
			<span class='cmsBottomBar'>
					<form name="redirectSearch" method="post" action="redirect.php" target="_blank">
					<input type="text" name="keyword" id="keyword" class="cmsTextarea2" style="vertical-align:bottom;"/>
					<button type="submit" name="direction_dir-bg" class="cmsBottomButton" value="sent"><img src="icons/bottom-dirbg.png" HEIGHT='14px' WIDTH='14px'></button><button type="submit" name="direction_google" class="cmsBottomButton" value="sent"><img src="icons/bottom-google.png" HEIGHT='14px' WIDTH='14px'></button><button type="submit" name="direction_wiki" class="cmsBottomButton" value="sent"><img src="icons/bottom-wikipedia.png" HEIGHT='14px' WIDTH='14px'></button><button type="submit" name="direction_gtranslate" class="cmsBottomButton" value="sent"><img src="icons/bottom-gtranslate.png" HEIGHT='14px' WIDTH='14px'></button>
					<span>$translationButtons</span>
			</span>
						
HTML;
}
else{
	echo "<center><font color=red>Само регистрирани потребители могат да се включат в превода</font></center>";
}
CMS_activitySave("edittext.php");

ramka("close");

require_once(FOOTERF);*/

//----------------------------------------------------------
//----------- CHANGEABLE PART ------------------------------
//----------------------------------------------------------

require_once("../../class2.php");
require_once(HEADERF);
		$user_id = USERID;
		$user_name = USERNAME;
require_once("./includes/require_all.php");

if ($_GET['sby']==0) {$_GET['sby']=1;}

?>
<script>
	function countTextchars (textare, tospan, addit) {
		var len = textare.value.length;
		$(tospan).text(len+'/'+addit);
	}
</script>
<?php

ramka("open");

$game_show_temp = mysql_fetch_array(mysql_query("select game_show from admin_panel where game_prefix='$CMS_pref'"));
$game_show = $game_show_temp[0];
if($game_show){

//Common variables
$CMS_file = $_GET['name'];
$CMS_page = get_page();
$posteded= $_POST['comment'];

		$per_page_r = $page_rows; //Number of rows to be displayed on 1 page
		$offset = $per_page_r*($CMS_page - 1); //Offset for the pages

//System functions
$CMS_pages=CMS_gamePagerInitiate();
CMS_dictionarySave();

//----------------------------------------------------------
//----------- UNCHANGEABLE PART ----------------------------
//----------------------------------------------------------
//---> Load text arrays for translation
$rowss = mysql_query("SELECT * FROM $text_table WHERE file_name = '".mysql_real_escape_string($CMS_file)."' and content <> '' LIMIT $per_page_r OFFSET $offset");
$arr_textid= array(); $arr_echoid= array(); $arr_translators= array(); $arr_content= array(); $arr_bg= array(); $arr_en= array(); $arr_en_slashed= array(); $key=0;
while($nextrow = mysql_fetch_array($rowss)){
		$content = trim($nextrow['content']); //Removing any spacebars from both ends
		if($CMS_game == "Oblivion" or $CMS_game == "AoM"){
			$content = htmlspecialchars(preg_replace("/\n/", " ", $content)); //Removing any new lines
		}
		else{
			$content = preg_replace("/\n/", " ", $content); //Removing any new lines
		}
		$content2 = trim($nextrow['english']); //Removing any spacebars from both ends
		if($CMS_game == "Oblivion"){
			$content2 = htmlspecialchars(preg_replace("/\n/", " ", $content2)); //Removing any new lines
		}
		else{
			$content2 = preg_replace("/\n/", " ", $content2); //Removing any new lines
		}
		$text_id = $nextrow['text_id'];
		$textarea = str_replace("[", "--IC001--", $text_id);
		$textarea = str_replace("]", "--IC002--", $textarea);
		$textarea = str_replace(":", "--IC003--", $textarea);
		$textarea = str_replace(" ", "--IC004--", $textarea);
		$textarea = str_replace("'", "--IC005--", $textarea);
		$textarea = str_replace(".", "--IC006--", $textarea);
		$textarea = str_replace("/", "--IC007--", $textarea);
		$textarea = str_replace("\\", "--IC008--", $textarea);
		$translator= $nextrow['translator'];
		$arr_textid[$key]= $textarea;
		$arr_echoid[$key]= $text_id;
		$arr_translators[$key]= $translator;
		$arr_content[$key]= $nextrow['content'];
		$arr_bg[$key]= $content;
		$arr_en[$key]= $content2;
		$arr_en_slashed[$key]= $content2;
		$key++;
} unset($key);

//---> Record the posted translation
if(isset($_POST['submit'])){
	$temp = ''; //Temporary file for containing transformed text for user translation
	$strcount=0;
	foreach ($arr_textid as $k => $w) {
		if($_POST['translation_'.$w] != "" and (preg_match("/[а-яА-Я]{2,}/u", $_POST['translation_'.$w]) or preg_match("/(_IGcoLLen)/", $w)) and !preg_match("/(<script)/", $_POST['translation_'.$w])){
			$strcount++;
			$tran = punctuation_check($_POST['translation_'.$w]);
			if(preg_match("/\</", $tran)){
				$tran = preg_replace("/</", "&lt;", $tran);
			}
			$temp .= (string)$arr_echoid[$k]."=>".$tran."\n";
		}
	}
	if(strlen($temp) > 0){
		$temp = mysql_real_escape_string($temp);
		$sql_sign_translation = "INSERT INTO $translations_table (translation, file_name, translator_id, translator_name, page) VALUES ('".$temp."', '".mysql_real_escape_string($CMS_file)."', '$user_id', '$user_name', '".mysql_real_escape_string($CMS_page)."')";
		mysql_query($sql_sign_translation);
		CMS_statistic1SAVE($strcount);
		autosysmessage1($strcount);
	}
}
unset ($temp, $tran);

//---> Load translated ids for for yellow, green and red markings
$rowss = mysql_query("SELECT translation FROM $translations_table WHERE file_name = '".mysql_real_escape_string($CMS_file)."' and page = '".mysql_real_escape_string($CMS_page)."'");
while($nextrow = mysql_fetch_array($rowss)){
	if($nextrow['translation'] != ''){
		$temp = explode("\n", $nextrow['translation']); //Dividing user's translation into rows
		foreach($temp as $v){
			$part = explode("=>", $v);
			$arr_transids[] = $part[0];
			$arr_transes[] = $part[1];
		}
	}
}
unset ($rowss, $nextrow, $temp, $v, $part);

CMS_gamePagerOverall_Save($arr_content, $arr_echoid);

//---> Back-button, page-tittle and legend
echo <<<HTML
	<center class='forumheader4' style='padding-bottom:14px;'><h1 style='border-bottom:0px; font-size:16px;'>$gamename ($CMS_file, стр.$CMS_page)</h1>
	</center>
	<div class='forumheader textGREY' style='font-weight:normal;'>
	<center style='margin-top:-13px;'>
	<table class="forumheader4"><tr>
	<td class="cmsMenuDivider unselectable"><<</td>
	<td class="cmsMenuTab cmsMenuTab-back unselectable" onclick="javascript: window.location='viewtext.php?game=$CMS_game&name=$CMS_file&page=$CMS_page';">НАЗАД</td>
	<td class="cmsMenuDivider unselectable">||</td>
	<td class="cmsMenuTab unselectable" onclick="javascript:toggle('legend001'); toggle3('search001'); toggle3('dict001');">Легенда</td>
	<td class="cmsMenuDivider unselectable">||</td>
	<td class="cmsMenuTab unselectable" onclick="javascript:toggle('search001'); toggle3('legend001'); toggle3('dict001');">Търсачка</td>
	<td class="cmsMenuDivider unselectable">||</td>
	<td class="cmsMenuTab unselectable" onclick="javascript:toggle('dict001'); toggle3('legend001'); toggle3('search001');">Речник</td>
	<td class="cmsMenuDivider unselectable">>></td>
	</tr></table>
	</center>

	<div id="legend001" style="display: none">
		<br>
		<img src="icons/edit1.png"> Позволява да се добави нов превод на вече одобрена реплика<br>
		<img src="icons/eng2.png"> Изтрива съдържанието на полето и въвежда английския текст на репликата заедно с код, който позволява тя да бъде одобрена като преведена. N.B: Ако натиснете по погрешка бутона и изгубите преведения в полето текст, шракнете с мишката вътре в полето и натиснете CTRL+Z.<br>
		<span class='textGREEN'>[...]</span><span class='textRED'>[...]</span>Текстът в квадратните скоби не се превежда и не е необходимо да се добавя в полето за писане на превода. В зависимост от играта, той може да показва кой говори, къде се развива действието и т.н. <span class='textRED'><br>Червеният</span> цвят означава, че репликата не е преведена, а <span class='textGREEN'>зеленият</span> е похвала за добре свършената работа :).
		N.B. Рефрешът на страницата няма да изтрие съдържанието на полетата. Направено е нарочно така, за да не се изгуби случайно текстът.
	</div>
HTML;

//--------------------------------------------------------------------
//------------------- SEARCH EMGINE ----------------------------------
//--------------------------------------------------------------------
//------------------- HTML visualization of the search engine
echo <<<HTML
	 <div id="search001" style="display: none;">
		 <br>
		 <form name="search" method="post" action="search.php?game=$CMS_game&go=yes" target="_blank">
		 <b>Търси: </b><input type="text" name="find" class="tbox cmsTextarea"/><b> в </b> 
		 <Select NAME="field" class="tbox cmsTextarea">
		 <Option VALUE="english">Оригиналния текст</option>
		 <Option VALUE="content">Преведените реплики</option>
		 </Select>
		 <input type="hidden" name="searching" value="yes" />
		 <input type="submit" name="search" value="Намери" class="button"/>
		 <br>
			 <input type="checkbox" name="capses" value="yes" >Големи/малки букви
			 <input type="checkbox" name="wholewords" value="yes" checked>Цели думи
		 </form>
	 </div>
HTML;
//------------------- Search executes in new page (where code is) ----
//------------------- SEARCH EMGINE END ------------------------------
//--------------------------------------------------------------------

echo '<div id="dict001" style="display: none">';
	CMS_dictionaryEcho();
echo '</div>';

$dict= CMS_dictionaryLoad();
$arr_bg2= CMS_insertDictTooltips($dict, $arr_en);


if($strcount>0) {
	echo "<br><center><div class='cmsMessage'><b> Репликите бяха запазени. Благодарим ви! </b></div></center>"; }	
CMS_lastApprovedEcho();

echo "<br>";
echo "</div><div class='forumheader4'>";
//---> Show form for acquiring translations
if($user_rights["ADD"]===1 && USERNAME!='USERNAME'){
	$text = ''; //It will contain the untranslated text for the edittext.php
	echo '<form action="" method="post" style="display: inline;">';
	echo "<div onmouseup=\"javascript:getSelText('keyword');\"><TABLE style='float:left;' CELLSPACING='0' CELLPADDING ='4' WIDTH='100%'>";
	foreach ($arr_echoid as $key => $value) {
		$text_id= $value; $content= $arr_bg[$key]; $content2= $arr_en[$key]; $content_slashed= $arr_en_slashed[$key]; $translator= $arr_translators[$key]; $content_tooltiped= $arr_bg2[$key];
		$bg_escaped=str_replace('"', '&quot;', $content); $bg_escaped=str_replace("'", "\'", $bg_escaped); $bg_escaped=str_replace("  ", " ", $bg_escaped); $bg_escaped=addslashes($bg_escaped);
		$textarea= $arr_textid[$key]; $charcount= mb_strlen($content);
		if ($key%2==1) { $class= "cmsRow1"; } else { $class= "cmsRow2"; }
		if(preg_match("/[а-яА-Я]{2,}/u", $content) OR preg_match("/(_IGcoLLen){1}/", $text_id)){
			echo <<<HTML
			<tr>
			<td style="vertical-align:top;" WIDTH="2%">
			<img src="icons/bullet-green.png" class="unselectable" alt="$"/>
			</td><td class="$class">
			<span id="main_$text_id" style="color:green;"></span> $content 
			(<span style="color:white;" class="unselectable">$translator</span>)
			<br>
			<div id="toggleText_$text_id">
			<span id="main2_$text_id" style='color:black;'></span> <span style='color:yellow;'>$content_tooltiped </span><br>
			<textarea name="translation_$textarea" cols="85" id="trans_$textarea" 
						style="color:white; border: 1px solid #FFF; border-radius: 1px; border-color: green;
						background:black; margin-top:-1px; margin-bottom:5px;"
						class="expand"
						onfocus="javascript:toggleSpan('main_$text_id', '[$text_id]'); toggleSpan('main2_$text_id', '[$text_id]');"
						onblur="javascript:toggleSpan('main_$text_id', ''); toggleSpan('main2_$text_id', '')"
HTML;
						if(preg_match("/(_IGcoLLen){1}/", $text_id)){
							echo <<<HTML
								onclick="javascript:autoInsert('trans_$textarea', '$bg_escaped'+'(IC101: Остави английския текст)');"></textarea>
HTML;
						}
						else{
							echo <<<HTML
								onclick="javascript:autoInsert('trans_$textarea', '$bg_escaped');"></textarea>
HTML;
						}
			echo <<<HTML
			<a onClick="document.getElementById('trans_$text_id').value = '$content_slashed(IC101: Остави английския текст)'"><img src="icons/eng2.png" style='margin-top:-1px; margin-bottom:5px;' alt="Добави" /></a>
			<br>
			</div>
			</td></tr>
			</div>
			</td></tr>
HTML;
		}
		else{
				if (in_array($text_id, $arr_transids)) { $icon= "bullet-yellow.png"; $color= "YELLOW"; } else { $icon= "bullet-red.png"; $color= "RED"; }
			$text .= $text_id."=".$content."\n";
			echo <<<HTML
			<tr>
			<td style="vertical-align:top;" WIDTH="2%" class='forumheader3 unselectable'>
			<img src="icons/$icon" alt="$" class="unselectable"/>
			</td><td class="forumheader3">
			<span id="main_$textarea" class="text$color"></span> $content_tooltiped
			<br>
			<textarea name="translation_$textarea" rows="1" id="trans_$textarea" 
						style="border-radius: 1px; margin-top:-1px; margin-bottom:5px; width: 95%"
						class="expand tbox borderGREY TBOX2"
						onkeyup="countTextchars(this, '#chars_$textarea', '$charcount')"
						onfocus="javascript:toggleSpan('main_$textarea', '[$text_id]')"
						onblur="javascript:toggleSpan('main_$textarea', '')"></textarea><span id="unneeded" class="unselectable"> </span>
						<img src="icons/eng2.png" style='cursor: pointer; float:right;' 
						alt="Добави" title='Остави на английски' class="unselectable" 
HTML;
						if(preg_match("/\"/", $content_slashed)){
							$content_slashed = str_replace('"', '\\"', $content_slashed);
							echo <<<HTML
							onClick='javascript:document.getElementById("trans_$textarea").value = "$content_slashed(IC101: Остави английския текст)";' />
HTML;
						}
						elseif(preg_match("/\'/", $content_slashed)){
							$content_slashed = str_replace("'", "\\'", $content_slashed);
							echo <<<HTML
							onClick="javascript:document.getElementById('trans_$textarea').value = '$content_slashed(IC101: Остави английския текст)';" />
HTML;
						}
						else{
							echo <<<HTML
							onClick="javascript:document.getElementById('trans_$textarea').value = '$content_slashed(IC101: Остави английския текст)';" />
HTML;
						}
						echo <<<HTML
			<br><div style='margin-top:-5px;'> <span id='chars_$textarea' style='margin-top:-5px; font-size: 12px; cursor:help;' title='Информативно съотношение на\nпреведения текст спрямо оригинала.\nСпазването му не е задължително.'></span></div></td></tr>
HTML;
		}
	}
		echo '</TABLE></div><span style="clear: left;"></span><br></div><div class="forumheader" style="font-weight:normal;">';
		echo '<center class="unselectable" style="margin-top:-15px;"><input name="submit" type="submit" value="Изпрати" class="button">';
		echo '</form>';
		echo " <a href='checked.php?game=$CMS_game&name=$CMS_file&page=$CMS_page' class='button' style='color:#B90004'>Проверена</a></center>";
		echo "<br>";
	
//---> Alpha-pager (Previous|Present|Next)		
		$p_prev=$CMS_page-1; $p_next=$CMS_page+1;
		if ($CMS_pages>1)
		{
			echo '<center class="unselectable" style="margin-top:-10px;">';
			if ($p_prev>0 AND $p_prev<=$CMS_pages) {
			echo "<a href='viewtext.php?game=$CMS_game&name=$CMS_file&page=$p_prev&sby=$_GET[sby]'><img src='icons/previous.png' alt='Предишна' style='vertical-align:middle;'/></a>";};
			echo "<a class='textWHITE'><b>$CMS_page</b></a>";
			if ($p_next>0 AND $p_next<=$CMS_pages) {
			echo "<a href='viewtext.php?game=$CMS_game&name=$CMS_file&page=$p_next&sby=$_GET[sby]'><img src='icons/next.png' alt='Следваща' style='vertical-align:middle;'/></a>";};	
			echo "</center>";
			echo '<br>';
		}
		
//---> Counting the comments
		$num_notes= mysql_fetch_array (mysql_query("SELECT COUNT(*) FROM cms_notes WHERE game = '".mysql_real_escape_string($CMS_game)."'"));
		$num_notes= $num_notes['0'];

//---------------------------- SECOND MENU START ------------------------------------
echo <<<HTML
				<div class="forumheader4">
				<center style='margin-top:-16px;'>
				<table class="forumheader4"><tr>
				<td class="cmsMenuDivider"><<</td>
				<td class="cmsMenuTab cmsMenuTab-back" onclick="javascript: window.location='filestable.php?game=$CMS_game&name=$CMS_file&page=$CMS_page';">НАЗАД</td>
				<td class="cmsMenuDivider">||</td>
				<td class="cmsMenuTab" onclick="javascript:toggle2('pages001'); toggle3('transes001'); toggle3('comments001');">Страници</td>
				<td class="cmsMenuDivider">||</td>
				<td class="cmsMenuTab" onclick="javascript:toggle2('transes001'); toggle3('pages001'); toggle3('comments001');">Преводи</td>
				<td class="cmsMenuDivider">||</td>
				<td class="cmsMenuTab" onclick="javascript:toggle2('comments001'); toggle3('pages001'); toggle3('transes001');">Бележки: <b class="cmsNumNotes"> $num_notes </b></td>
				<td class="cmsMenuDivider">>></td>
				</tr></table>
				</center>
				<br>
HTML;
//---------------------------- SECOND MENU END ------------------------------------

//---> Alpha-pager (Page list)
if($_GET['go'] != "pending" AND $_POST['editoract'] != "yes") { echo "<div id='pages001' style='display:block'>"; }
else { echo "<div id='pages001' style='display:none'>"; }
	/*$all_pages_array = array(); $pages_array = array();
	$pages_status= CMS_gamePagerOverall_Load();
	for($i=1;$i<=$CMS_pages;$i++){ 
		if ($i==$CMS_page) { $pages_array[] = "button textWHITE"; }
		elseif ($pages_status[$i]== "yellow") { $pages_array[] = "button textYELLOW"; }
		elseif ($pages_status[$i]== "green") { $pages_array[] = "button textGREEN"; }
		else { $pages_array[] = "button textRED"; }
		}*/
	$per = 0;
	if ($CMS_pages>999) {$TDwitdh="35px";$cons=18;} elseif ($CMS_pages>99) {$TDwitdh="25px";$cons=24;} else {$TDwitdh="15px";$cons=30;}; // Набързо скалъпвам широчината и броя на колоните в pager-а, съобразно броя на страниците, за да са с еднаква ширина бутоните в него
	echo "<table style='text-align:center;'><tr>";
	for($i=1;$i<=$CMS_pages;$i++){
		if($per%$cons == 0){
			echo "</tr>";
		}
		if($per%$cons == 0){
			echo "<tr>";
		}
		//$a= $i-1; $TDcolor= $pages_array[$a];
		if($i==$CMS_page){
			echo <<<HTML
					<td class='unselectable' style='width:$TDwitdh;color:#FFF;border: 1px solid #FFF;'>$i</td>
HTML;
		}
		else{
			$checked_pages = mysql_fetch_array(mysql_query("select * from cms_checked where game_name = '$CMS_game' and file_name = '$CMS_file' and file_page = $i"));
			if($checked_pages['checked']==1){
				echo <<<HTML
					<td class='unselectable' style='width:$TDwitdh;color:green;border: 1px solid green;cursor: pointer;'
					onclick="javascript: window.location.href='edittext.php?game=$CMS_game&name=$CMS_file&page=$i';">$i</td>
HTML;
			}
			else{
				echo <<<HTML
					<td class='unselectable' style='width:$TDwitdh;color:red;border: 1px solid red;cursor: pointer;'
					onclick="javascript: window.location.href='edittext.php?game=$CMS_game&name=$CMS_file&page=$i';">$i</td>
HTML;
			}
		}
		$per++;
	}
	echo "</table>";
echo "</div>";

//---> Approve/Disapprove status or delete the translation
if($_GET['go'] === "pending" OR $_POST['editoract'] === "yes") { echo "<div id='transes001' style='display:block'>"; }
else { echo "<div id='transes001' style='display:none'>"; }
	$result_all_id = mysql_query("SELECT id FROM $translations_table");
	while($array_all_id = mysql_fetch_array($result_all_id)){
		$id_translation = array_shift($array_all_id);
		if(isset($_POST["approve_$id_translation"])){
			$trans = $_POST["trans_$id_translation"];
			mysql_query("UPDATE $translations_table SET status = 'Одобрен', translation = '".mysql_real_escape_string($trans)."' WHERE id = '$id_translation' AND file_name = '".mysql_real_escape_string($CMS_file)."'");
			
			$translator= mysql_query("SELECT translator_name FROM $translations_table WHERE id = '$id_translation' LIMIT 1");
			$translator= mysql_fetch_array($translator);
			$translator= $translator['translator_name'];
			
			$translation = explode("\n", $trans); //Dividing user's translation into rows
			$count= count($translation);
			$codes = array(); //It will contain codes from user's translation
			foreach($translation as $v){
				$g = explode("=>", $v);
				$codes[] = $g[0];
			}
			foreach($codes as $key => $code){
				$code_repl= 0;
				$t = explode("=>", $translation[$key]);
				if (preg_match("/(_IGcoLLen)/", $code)) { $code_repl= str_replace ("_IGcoLLen", "", $code);};
				if (preg_match("/(IC101: Остави английския текст)/", $t[1])) {  // Сменяме text_id-то на файла, за да бъде считан низът оттук-нататък като преведен
					$t[1]= str_replace ("(IC101: Остави английския текст)", "", $t[1]);
					if ($code_repl!==0) {$code_repl= $code_repl."_IGcoLLen";};
					if ($code_repl===0) {$code_repl= $code."_IGcoLLen";};
				}
				$code= mysql_real_escape_string($code);
				if ($code_repl!==0) {
					$code_repl= mysql_real_escape_string($code_repl);
					mysql_query("UPDATE $text_table SET text_id = replace(text_id, '$code', '$code_repl') WHERE text_id = '$code' AND file_name = '".mysql_real_escape_string($CMS_file)."'");
					$code= $code_repl;
				}
				$s= array_search($code, $arr_echoid); $translator_back= $translator;
				if ($arr_translators[$s]!="original") { $translator=$arr_translators[$s]; }
				mysql_query("UPDATE $text_table SET content = '".mysql_real_escape_string($t[1])."', translator = '".mysql_real_escape_string($translator)."' WHERE text_id = '$code' AND file_name = '".mysql_real_escape_string($CMS_file)."'");
				$translator= $translator_back;
				
				//translating all the same rows
				$x = mysql_query("select * from $text_table where text_id = '$code' and file_name = '".mysql_real_escape_string($CMS_file)."'");
				$y = mysql_fetch_array($x);
				$id = $y['text_id'];
				$eng = $y['english'];
				$bg = $y['content'];
				$tr = $y['translator'];
				$rrr = mysql_query("select * from $text_table where english = binary '".mysql_real_escape_string($eng)."'");
				if(mysql_num_rows($rrr)){
					if(preg_match("/(_IGcoLLen)/", $id)){
						mysql_query("UPDATE $text_table SET text_id = concat(text_id, '_IGcoLLen'), content = '".mysql_real_escape_string($bg)."', translator = '".mysql_real_escape_string($tr)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator = 'original'");
						mysql_query("UPDATE $text_table SET text_id = concat(text_id, '_IGcoLLen'), content = '".mysql_real_escape_string($bg)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator != 'original'");
					}
					else{
						mysql_query("UPDATE $text_table SET content = '".mysql_real_escape_string($bg)."', translator = '".mysql_real_escape_string($tr)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator = 'original'");
						mysql_query("UPDATE $text_table SET content = '".mysql_real_escape_string($bg)."' WHERE english = binary '".mysql_real_escape_string($eng)."' and translator != 'original'");
					}
				}
			}
			CMS_lastApprovedSave($count, $translator);
			$wordsall=mysql_fetch_array(mysql_query("SELECT SUM( LENGTH(english) - LENGTH(REPLACE (english, ' ', ''))+1) FROM $text_table"));
			$wordsdone= mysql_fetch_array(mysql_query("SELECT SUM( LENGTH(english) - LENGTH(REPLACE (english, ' ', ''))+1) FROM $text_table WHERE content REGEXP '[а-яА-Я]{1,}'"));
			mysql_query("UPDATE admin_panel SET wordsall='$wordsall[0]', wordsdone='$wordsdone[0]' WHERE game_prefix='$CMS_pref'");
			echo "<meta http-equiv=\"refresh\" content=\"0;edittext.php?game=$CMS_game&name=$CMS_file&page=$CMS_page\" />";
		}
		if(isset($_POST["disapprove_$id_translation"])){
			mysql_query("UPDATE $translations_table SET status = 'Неодобрен' WHERE id = '$id_translation'");
		}
		if(isset($_POST['delete_'.$id_translation])){
			mysql_query("DELETE FROM $translations_table WHERE id = '$id_translation'");
		}
	}
	
//---> Show all recorded translation for that text in that page
	$result_translations = mysql_query("SELECT * FROM $translations_table WHERE file_name = '".mysql_real_escape_string($CMS_file)."' and page = '".mysql_real_escape_string($CMS_page)."' ORDER BY id DESC");
	while($array_translations = mysql_fetch_array($result_translations)){
		if($user_rights["ADD"]===1 AND $user_rights["APPROVE"]!==1 and $user_name != "guybrush"){
			$status = $array_translations['status'];
			if($status === 'Одобрен'){ $status_color = "GREEN"; } elseif($status === 'Неодобрен'){ $status_color = "RED"; } else { $status_color = "YELLOW"; }
			echo "<table><tr><td>";
			echo "<div class='apview-border border$status_color' id='".$array_translations['id']."'>";
			echo "<a href=/user.php?id.".$array_translations['translator_id']." name=".$array_translations['id'].">".$array_translations['translator_name']."</a> <span class='smalltext' style='float: right;'>".$array_translations['time']."</span><br />";
			echo nl2br($array_translations['translation']);
			$status = $array_translations['status'];
			echo "<br><span class='text$status_color'>".$status."</span><br />";
			echo "</div>";
			echo "</td></tr></table>";
		}
		
//---> Show translsation areas for admin + Approve/disapprove/delete translations
		if($user_rights["APPROVE"]===1 or $user_name == "guybrush"){
			$tran = ''; $pretran = '';
			$status = $array_translations['status'];
			$waiting_text = trim($array_translations['translation']);
				$waiting_rows = explode("\n", $waiting_text);
				foreach ($waiting_rows as $nextrow) {
					$exploded = explode("=>", $nextrow);
					$waiting_id[] = $exploded[0];
				}
				foreach ($waiting_id as $v) {
					$key = array_search($v, $arr_echoid, true);
					$pretran .= "<span class='textYELLOW'>".$arr_echoid[$key]."=</span>".$arr_content[$key]."<br>";
				}
				unset ($waiting_rows, $exploded, $waiting_id); 
			if($status == 'Одобрен'){ $status_color = "GREEN"; } elseif($status == 'Неодобрен'){ $status_color = "RED"; } else { $status_color = "YELLOW"; }
			echo "<table><tr><td>";
			echo "<div class='apview-border border$status_color' id='".$array_translations['id']."'>";
			echo "<a href=/user.php?id.".$array_translations['translator_id'].">".$array_translations['translator_name']."</a> <span class='smalltext' style='float: right;'>".$array_translations['time']."</span><br />";
			echo '<form action="" method="post">';
				if ( $_GET['go']=="pending" ) {
					echo '<textarea name="trans_'.$array_translations['id'].'" id="trans" class="expand tbox borderGREY TBOX2" style="width:99%;">'.$waiting_text.'</textarea> </br>';
				}
				else {
					echo '<textarea name="trans_'.$array_translations['id'].'" id="trans" class="expand tbox borderGREY TBOX2" style="width:99%;">'.$waiting_text.'</textarea> </br>';
				}
			echo '<a class="textGREY"><u>Настоящо състояние на репликите</u>: </a>(<a href="javascript:toggle(\'tip_'.$array_translations['id'].'\');">Покажи</a>)';
			echo '<div id="tip_'.$array_translations['id'].'" style="display: none">';
			echo $pretran;
			echo '</div>';
			echo "<br><center class='forumheader3 text$status_color'>".$status."</center>";
			echo '<center class="forumheader" ><input type="hidden" name="editoract" value="yes">';
			if($status == 'Одобрен'){
				echo '<input name="approve_'.$array_translations['id'].'" type="submit" value="Одобри" style="text-decoration: line-through;" class="button" disabled>';
				echo '<input name="disapprove_'.$array_translations['id'].'" type="submit" value="Отхвърли" style="text-decoration: line-through;" class="button" disabled>';
			}
			elseif($status == 'Неодобрен'){
				echo '<input name="approve_'.$array_translations['id'].'" type="submit" value="Одобри" class="button">';
				echo '<input name="disapprove_'.$array_translations['id'].'" type="submit" value="Отхвърли" style="text-decoration: line-through;" class="button" disabled>';
			}
			else{
				echo '<input name="approve_'.$array_translations['id'].'" type="submit" value="Одобри" class="button">';
				echo '<input name="disapprove_'.$array_translations['id'].'" type="submit" value="Отхвърли" class="button">';
			}
			echo '<input name="delete_'.$array_translations['id'].'" type="submit" value="Изтрий" class="button"></center>';
			
			echo '</form>';
			echo "</div>";
			echo "</td>";
			echo "</tr>";
			echo "</table>";
		}
	}
echo "</div>";

if(isset($_POST['comsubmit'])) { echo "<div id='comments001' style='display:block'>"; }
else { echo "<div id='comments001' style='display:none'>"; }
			if (isset($posteded)) {
				$posteded = strtoupper($posteded); 
				$posteded = strip_tags($posteded); 
				$posteded = trim ($posteded);
			}
			if(isset($_POST['comsubmit']) AND $posteded != '') {
				mysql_query("INSERT INTO cms_notes (`note`, `game`, `user_id`, `user_name`) VALUES ('".mysql_real_escape_string($posteded)."', '".mysql_real_escape_string($CMS_game)."', '$user_id', '$user_name')");
			}			

			$temp=0;
			$notes= mysql_query("SELECT * FROM cms_notes WHERE game = '".mysql_real_escape_string($CMS_game)."' ORDER by time DESC");
			while($note = mysql_fetch_array( $notes )) {
				$arr_notes[$temp]['note']= $note['note'];
				$arr_notes[$temp]['status']= $note['status'];
				$arr_notes[$temp]['time']= $note['time'];
				$arr_notes[$temp]['user']= $note['user_name'];
				$temp++;
			}
			
			if ($temp == 0) { echo "<center class='textWHITE'>Все още няма добавени бележки.</center>"; }
			echo "<div class='textWHITE'>";
			$temp=1;
			foreach ($arr_notes as $key => $note) {
				  $note['time']= months_inBG(date("j F : H:i", strtotime($note['time'])));
				  if ($temp%2===0) { $class= "cmntRow1"; $class2= "cmntUser1"; } else { $class= "cmntRow2"; $class2= "cmntUser2"; }
				  echo "<div class='forumheader3'><span class='$class2'>".$note['user']."</span> <span class='cmntDate'>".$note['time']."</span><br>";
				  echo "<img src='icons/bullet-white.png' alt=' ' class='unselectable'/> ".$note['note']."<br>";
				  echo "</div>";
				  $temp++;
			}
			echo "</div>";
			echo "<div class='forumheader3'>	
					<form method='post' action='viewtext.php?game=$CMS_game&name=$CMS_file&page=$CMS_page&sby=$_GET[sby]#menu2'>
					<br><center><textarea name='comment' cols='50' id='comment' class='tbox expand48-150'>Вашият коментар...</textarea>
					<br><input type='submit' value='Изпрати' name='comsubmit' class='button'></center>
					</form><br /> 
				  </div>";
echo "</div>";

$translationButtons= "";
if($user_rights["APPROVE"]===1){
	$pendings= CMS_pendingTranslationsLoad("for game");
	if (!isset($_GET['pendingID'])) {
		$filestart= array_search($CMS_file, $pendings);
		foreach ($pendings as $index => $pending) {
			if ($pending['page']<$CMS_page AND $pending['file_name']==$CMS_file) {$prev_key= $index;}
			elseif ($pending['page']>=$CMS_page AND $pending['file_name']==$CMS_file) {$next_key= $index; break;}
			else {
					$temp= $filestart-1;
					if (isset($pendings[$temp])) { $prev_key= $temp; }
					$temp= $filestart+1;
					if (isset($pendings[$temp])) { $next_key= $temp; }
			}
		}
	}
	else {
		$present= $_GET['pendingID'];
		$temp= $present-1;
		if (isset($pendings[$temp])) { $prev_key= $temp; }
		$temp= $present+1;
		if (isset($pendings[$temp])) { $next_key= $temp; }
	}
	$tmp_name= $pendings[$prev_key]['file_name']; $tmp_page= $pendings[$prev_key]['page']; $tmp_id= $pendings[$prev_key]['id'];
	if (isset($prev_key)) {$prev="viewtext.php?game=$CMS_game&name=$tmp_name&page=$tmp_page&pendingID=$prev_key&go=pending&sby=$_GET[sby]#$tmp_id";}
	$tmp_name= $pendings[$next_key]['file_name']; $tmp_page= $pendings[$next_key]['page']; $tmp_id= $pendings[$next_key]['id'];
	if (isset($next_key)) {$next="viewtext.php?game=$CMS_game&name=$tmp_name&page=$tmp_page&pendingID=$next_key&go=pending&sby=$_GET[sby]#$tmp_id";}
	if (isset($prev)) {$translationButtons.="<a href='$prev' style='vertical-align:middle;'>◄</a>";}
	$translationButtons.="<span class='cmsPendingTranses' style='vertical-align:middle;'>".$pendings['count']."</span>";
	if (isset($next)) {$translationButtons.="<a href='$next' style='vertical-align:middle;'>►</a>";}
	$translationButtons= "<button title='Всички преводи' class='cmsBottomButton' onClick=window.open('apall.php?game=$CMS_game')><img src='icons/bottom-approve.png' HEIGHT='14px' WIDTH='14px'></button>".$translationButtons;
	$translationButtons= "<span style='color:#0D0D0D;' class='unselectable'>|| </span>".$translationButtons;
}
	
echo <<<HTML
			<span class='cmsBottomBar'>
					<form name="redirectSearch" method="post" action="redirect.php" target="_blank" style="display: inline;">
					<input type="text" name="keyword" id="keyword" class="cmsTextarea2" style="vertical-align:bottom;"/>
					<button title="Потърси в речник" type="submit" name="direction_dir-bg" class="cmsBottomButton" value="sent"><img src="icons/bottom-dirbg.png" HEIGHT='14px' WIDTH='14px'></button><button title="Потърси с Google" type="submit" name="direction_google" class="cmsBottomButton" value="sent"><img src="icons/bottom-google.png" HEIGHT='14px' WIDTH='14px'></button><button title="Потърси в Уикипедия" type="submit" name="direction_wiki" class="cmsBottomButton" value="sent"><img src="icons/bottom-wikipedia.png" HEIGHT='14px' WIDTH='14px'></button><button type="submit" title="Преведи с Google Translate" name="direction_gtranslate" class="cmsBottomButton" value="sent"><img src="icons/bottom-gtranslate.png" HEIGHT='14px' WIDTH='14px'></button>
					</form>
					<span>$translationButtons</span>
						
HTML;
//if($user_name == "HeBuguM" || $user_name == "Mnementh") {
echo "<span>Цветова гама: <a href=\"#\" 
onclick=\"setActiveStyleSheet('black'); 
return false;\">Черна</a> | 

<a href=\"#\" 
onclick=\"setActiveStyleSheet('white'); 
return false;\">Бяла</a>
</span>";
//}
echo "</span>";

}else{
	echo "<center><font color=red>Само регистрирани потребители могат да се включат в превода</font></center>";
}
CMS_activitySave("viewtext.php");
echo "</div></div><div class='forumheader2'></div>";
ramka("close");
$text= null;
require_once(FOOTERF);

}else echo "Не е уточнена игра, която да бъде показана, играта е преведена, или нямате достъп до нея. Извиняваме се за неудобството.";
?>